# -*— coding: utf-8 -*-
# @Time: 2024/6/28 11:17
# @Author :Lin Zhou
# @Email : lin1013143@163.com
# @File : operation_log_utils.py
# @SoftWare: PyCharm
from functools import wraps

from django.contrib.contenttypes.models import ContentType

from django.contrib.auth.decorators import login_required

from system.models import OperationLog


def log_create_action(model_class):
    """装饰器，用于记录创建操作日志"""

    @wraps
    def decorator(func):
        # @login_required
        def wrapper(request, *args, **kwargs):
            response = func(request, *args, **kwargs)
            print(response)
            if response.status_code == 200:
                # 假设func返回的是JsonResponse且创建操作成功
                obj = model_class.objects.get(pk=response.json().get('id'))
                log_action(request.user, obj, OperationLog.ACTION_CREATE, change_message="对象创建")
            return response

        return wrapper

    return decorator


def log_update_action(model_class):
    """装饰器，用于记录更新操作日志"""

    @wraps
    def decorator(func):
        # @login_required
        def wrapper(request, *args, **kwargs):
            obj = model_class.objects.get(pk=kwargs.get('pk'))  # 假设pk作为URL参数传递
            old_obj_data = model_class.objects.filter(pk=obj.pk).values().first()  # 记录旧数据（可选，根据需要）
            response = func(request, *args, **kwargs)
            if response.code == 200:
                # 记录更新日志
                log_action(request.user, obj, OperationLog.ACTION_UPDATE,
                           "对象更新，变更详情：{}".format(get_changes(old_obj_data, obj)))
            return response

        return wrapper

    return decorator


def get_changes(old_data, new_obj):
    """简单示例，比较对象更改前后差异，返回变更信息字符串"""
    changes = []
    for field in old_data.keys():
        if getattr(new_obj, field) != old_data[field]:
            changes.append(f"{field}: {old_data[field]} -> {getattr(new_obj, field)}")
    return "; ".join(changes) if changes else "无明显变更"


def log_action(user, instance, action_flag, change_message=''):
    """记录操作日志的函数"""
    content_type = ContentType.objects.get_for_model(instance)
    print("记录操作日志的函数")
    OperationLog.objects.create(
        user=user,
        content_type=content_type,
        object_id=instance.pk,
        object_repr=str(instance),
        action_flag=action_flag,
        change_message=change_message,
    )